<?php

namespace App\Http\Controllers;

use App\Models\Sound;
use Illuminate\Http\Request;
use App\Models\Word;
use App\Models\Uword;
use App\Models\Collect;

class WordController extends Controller
{

    protected $id = 'wx2f158ff2c11306cf';
    public function UseraddWord(Request $request) {
        $id = $request->get('id');
        $word = $request->get('word');
        $ch = $request->get("ch");
        $collect = $request->get("collect");
        //判断单词是否重复,保证唯一性

        $res = Uword::where("word",$word)->where("user",$id)->get();

        if($res->first()){
            return response()->json(["status"=>0]);
        }
        //var_dump($collect);
       // echo $id,$word,$ch;

        if($id=='null'||$word=='null'){
            return response()->json(["status"=>0]);
        }else {
            $res = Uword::create(["user"=>$id,"collect"=>$collect,"word"=>$word,"ch"=>$ch]);
            //var_dump(Word::find(10));
            if($res){
                return response()->json([
                   "status"=>200
                ]);
            }
        }

    }

    public function Findword(Request $request) {
          $page = $request->get('page');
          $data = Uword::whereBetween("id",[$page*10-9,$page*10])->get();

          if($data){
              return response()->json([
                  "status"=>200,
                  "data" => $data
              ]);
          }

    }

    //删除单词，真删除，切勿小心

    public function Delword(Request $request){
        $word = $request->get('word');
        $user = $request->get('openid');
        $collect = $request->get("collect");

        $res = Uword::where("word",$word)->where("user",$user)->where("collect",$collect)->get();

        $data = $res[0]->delete();

        if($data){
            return response()->json([
                "status"=>200,
                "data" => $data
            ]);
        }

    }

    //随机20个单词
    public function Rangeword(){

        $tmp = range(1,5000);

        $arr = array_rand($tmp,20);

        $data = Word::whereIn("id",$arr)->get();
        foreach ($data as $key=>$val){
            $data[$key]['CH_s'] = mb_substr($val['CH'],0,12,'utf8');
        }
        if($data){
            return response()->json([
                "status"=>200,
                "data" => $data
            ]);
        }

    }

    //db82165778db11ff9bc3d25082266762
    //小程序登录获取opneid
    public function Wxlogin(Request $request) {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->id.'&secret='.getenv('WX_TOKEN').'&js_code='.$request->get('code').'&grant_type=authorization_code';
        $client = new \GuzzleHttp\Client(['verify'=>false]);
        $data =  $client->request('GET',$url);
        $data = $data->getBody();
        $data = json_decode($data,true);

        //判断是否建立默认收藏夹，否则自动建立
//       $res =  Collect::where("user",$data['openid'])->where("collect_name","默认收藏本")->get();
//
//       if(!$res->first()){
//           Collect::create(["user"=>$data['openid'],"collect_name"=>"默认收藏本"]);
//       }


        return response()->json($data);


    }

    //获取单词发音链接
    public function Sound(Request $request){
        $word = $request->get('word');
        $res = Sound::where("word",$word)->get();
        if(!$res->first()){
            $json = file_get_contents('https://www.dictionaryapi.com/api/v3/references/collegiate/json/'.$word.'?key='.getenv('TOKENSOUND'));
            $json = json_decode($json,TRUE);
            // var_dump($json[0]['meta']);
            $psr = $json[0]["hwi"]["prs"];
            $sound = null;
            foreach($psr as $key=>$val){
                if(array_key_exists('sound',$val)){
                    $sound = $val['sound']['audio'];
                }
            }
            if($sound == null){
                return response()->json([
                    "status"=>-1
                ]);
            }

            // var_dump($sound);
            $stat1 = substr($sound,0,1);
            $isnum = preg_match('/[0-9_]/', $stat1);
            $stat = substr($sound,0,2);
            $isgg = $stat=='gg'?1:0;
            $stat = substr($sound,0,3);
            $isbix = $stat=='bix'?1:0;
            if($isnum == 1){
                $file ='https://media.merriam-webster.com/soundc11/number/'.$sound.'.wav';
            }
            elseif ($isgg==1){
                $file = 'https://media.merriam-webster.com/soundc11/gg/'.$sound.'.wav';
            }
            elseif($isbix==1){
                $file = 'https://media.merriam-webster.com/soundc11/bix/'.$sound.'.wav';
            }else{
                $file = 'https://media.merriam-webster.com/soundc11/'.$stat1.'/'.$sound.'.wav';
            }
            //写入数据
            $res = Sound::create(["word"=>$word,'link'=>$file]);
            $fileres = file_get_contents($file);
            file_put_contents("/var/www/html/collect/public/sound/".$word.".wav",$fileres);
        }
        $file = 'https://wxapi.kaycn.com/sound/'.$word.'.wav';
        if($res){
            return response()->json([
               "status"=>200,
                "sound"=>$file
            ]);
        }

    }
}
